package bookmanagement.book;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BookList {
    private static final List<Book> books = new ArrayList<>();
    private static final List<String> allBooksName = new ArrayList<>();

    static {
        books.add(new Book("水浒传","施耐庵",85.5,"小说"));
        books.add(new Book("三国演义","罗贯中",120.6,"小说"));
        books.add(new Book("红楼梦","曹雪芹",99.9,"小说"));
        books.add(new Book("西游记","吴承恩",66.6,"小说"));

        allBooksName.add("水浒传");
        allBooksName.add("三国演义");
        allBooksName.add("红楼梦");
        allBooksName.add("西游记");
    }

    public void addBook(Book book) {
        books.add(book);
        allBooksName.add(book.getName());
    }

    public boolean isBookContains(String booksName) {
        if (allBooksName.contains(booksName)) {
            return true;
        }
        return false;
    }

    public void displayAllBooks() {
        Iterator<Book> iterator = books.iterator();
        while (iterator.hasNext()) {
            Book book = iterator.next();
            System.out.println(book);
        }
    }

    private Book findBookByName(String booksName) {
        if (allBooksName.contains(booksName)) {
            Iterator<Book> iterator = books.iterator();
            while (iterator.hasNext()) {
                Book book = iterator.next();
                if (book.getName().equals(booksName)) {
                    return book;
                }
            }
        }else {
            System.err.println("书籍不存在！");
        }
        return null;
    }

    public void borrowBook(String booksName) {
        Book book = findBookByName(booksName);
        if (book == null) {
            return;
        }
        if (book.isBorrowed()) {
            System.err.println(booksName+"已经被借出去啦~下次再来吧~");
        }else {
            System.out.println("借书成功~");
            book.setBorrowed(true);
        }
    }

    public void returnBook(String booksName) {
        Book book = findBookByName(booksName);
        if (book == null) {
            return;
        }
        if (!book.isBorrowed()) {
            System.err.println("书籍还在图书馆，没有借出哦，请检查书籍名称~");
        }else {
            System.out.println("还书成功");
            book.setBorrowed(false);
        }
    }

    public boolean findBooks(String booksName) {
        Book book = findBookByName(booksName);
        return ! (book == null);
    }

    public boolean removeBooks(String booksName) {
        Book book = findBookByName(booksName);
        if (book == null) {
            return false;
        }else {
            books.remove(book);
            allBooksName.remove(booksName);
            return true;
        }
    }

    public void updateBooks(String booksName,double price,String type) {
        Book book = findBookByName(booksName);
        book.setPrice(price);
        book.setType(type);
    }
}
